package com.sdcqjy.mylibrary.http;

import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import com.sdcqjy.mylibrary.FileOperateUtil;
import com.sdcqjy.mylibrary.LibApp;
import com.sdcqjy.mylibrary.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * Created by 52463 on 2018/3/23.
 */

public class DownloadManage {
    private static DownloadManage downloadManage;

    public static DownloadManage getInstance() {
        if (downloadManage == null) {
            synchronized (DownloadManage.class) {
                if (downloadManage == null) {
                    downloadManage = new DownloadManage();
                }
            }
        }
        return downloadManage;
    }

    private DownloadManage() {
        processList = new ArrayList<>();
        httpHashMap = new HashMap<>();
        backHashMap = new HashMap<>();
        handler = new Handler(Looper.getMainLooper());
        //查找文件，发现没有的就清除
        DownloadDB downloadDB = new DownloadDB(LibApp.getContext());
        downloadDB.clearData();
        downloadDB.close();
    }

    //正在执行的任务，取消或已暂停不算
    private List<DownloadMode> processList;
    private HashMap<DownloadMode, DownloadHttp> httpHashMap;
    private HashMap<DownloadMode, DownloadCallBack> backHashMap;
    private Handler handler;

    //移除监听
    public synchronized void removeCallBack(DownloadCallBack callBack) {
        if (callBack == null) return;
        Set<DownloadMode> downloadModes = backHashMap.keySet();
        List<DownloadMode> keyList = new ArrayList<>();
        for (DownloadMode key : downloadModes) {
            if (callBack.equals(backHashMap.get(key))) {
                keyList.add(key);
            }
        }
        for (DownloadMode key : keyList) {
            backHashMap.remove(key);
        }
    }

    //重新加入监听
    public synchronized void addCallBack(DownloadTask downloadTask, DownloadCallBack callBack) {
        String url = downloadTask.getUrl();
        if (TextUtils.isEmpty(url) || TextUtils.isEmpty(downloadTask.getName())) return;
        DownloadMode mode = null;
        for (int i = 0; i < processList.size(); i++) {
            mode = processList.get(i);
            if (mode.name.equals(downloadTask.getName())) break;
        }
        if (mode == null || backHashMap.containsKey(mode)) return;
        backHashMap.put(mode, callBack);
    }

    public void hasDownload(DownloadTask downloadTask) {
    }

    //执行任务
    public synchronized void executionTask(DownloadTask downloadTask) {
        String url = downloadTask.getUrl();
        if (TextUtils.isEmpty(url) || TextUtils.isEmpty(downloadTask.getName())) {
            Logger.e("--DownloadManage--executionTask--", "--下载失败--name出错--");
            return;
        }
        switch (downloadTask.getType()) {
            case DownloadTask.DownloadTypeStart:
                startTask(downloadTask);
                break;
            case DownloadTask.DownloadTypePause:
                pauseTask(downloadTask);
                break;
            case DownloadTask.DownloadTypeCancel:
                cancelTask(downloadTask);
                break;
        }
    }

    //开始一个任务
    private void startTask(DownloadTask downloadTask) {
        String name = downloadTask.getName();
        DownloadMode mode = null;
        for (int i = 0; i < processList.size(); i++) {
            mode = processList.get(i);
            if (mode.name.equals(name)) break;
        }
        //存在则不管
        if (mode != null) return;
        DownloadDB downloadDB = new DownloadDB(LibApp.getContext());
        List<DownloadMode> taskOfName = downloadDB.getTaskOfName(name);
        if (taskOfName != null && taskOfName.size() > 0) mode = taskOfName.get(0);
        if (mode == null) {//从头下载
            mode = new DownloadMode();
            mode.name = name;
            mode.url = downloadTask.getUrl();
            String fileName = FileOperateUtil.getFileNameOfUrl(downloadTask.getUrl());
            if (TextUtils.isEmpty(downloadTask.path)) {
                mode.path = FileOperateUtil.getInstance().getFolderPath(FileOperateUtil.ROOT) + fileName;
            } else {
                mode.path = downloadTask.path + fileName;
            }
            downloadDB.insertTask(mode);
        }
        downloadDB.close();
        //开启Http
        DownloadHttp downloadHttp = new DownloadHttp(mode).setDownloadManage(this);
        processList.add(mode);
        httpHashMap.put(mode, downloadHttp);
        if (downloadTask.downloadCallBack != null)
            backHashMap.put(mode, downloadTask.downloadCallBack);
        downloadHttp.start();
    }

    //暂停一个任务
    private void pauseTask(DownloadTask downloadTask) {
        String name = downloadTask.getName();
        DownloadMode mode = null;
        for (int i = 0; i < processList.size(); i++) {
            mode = processList.get(i);
            if (mode.name.equals(name)) break;
        }
        //不管
        if (mode == null) return;
        if (httpHashMap.containsKey(mode)) {
            httpHashMap.get(mode).stop();
        }
    }

    //取消一个任务
    private void cancelTask(DownloadTask downloadTask) {
        String name = downloadTask.getName();
        DownloadMode mode = null;
        for (int i = 0; i < processList.size(); i++) {
            mode = processList.get(i);
            if (mode.name.equals(name)) break;
        }
        //删数据
        DownloadDB downloadDB = new DownloadDB(LibApp.getContext());
        downloadDB.deleteTask(name);
        downloadDB.close();
        //不管
        if (mode == null) return;
        if (httpHashMap.containsKey(mode)) {
            httpHashMap.get(mode).stop();
        }
    }

    private synchronized void removeTask(DownloadMode mode) {
        processList.remove(mode);
        backHashMap.remove(mode);
        httpHashMap.remove(mode);
    }

    private synchronized DownloadCallBack getCallBack(DownloadMode mode) {
        DownloadCallBack callBack = null;
        if (backHashMap.containsKey(mode)) callBack = backHashMap.get(mode);
        return callBack;
    }

    //下载失败
    protected synchronized void onError(final DownloadMode mode) {
        //通知进度
        handler.post(new Runnable() {
            public void run() {
                DownloadCallBack callBack = getCallBack(mode);
                if (callBack != null) {
                    callBack.onError(mode);
                    removeTask(mode);
                }
            }
        });
    }

    //下载停止
    protected synchronized void onStop(final DownloadMode mode) {
        //存库
        DownloadDB downloadDB = new DownloadDB(LibApp.getContext());
        downloadDB.updateTask(mode);
        downloadDB.close();
        //通知进度
        handler.post(new Runnable() {
            public void run() {
                DownloadCallBack callBack = getCallBack(mode);
                if (callBack != null) {
                    callBack.onStop(mode);
                    removeTask(mode);
                }
            }
        });
    }

    //下载成功
    protected synchronized void onResponse(final DownloadMode mode) {
        //存库
        DownloadDB downloadDB = new DownloadDB(LibApp.getContext());
        downloadDB.deleteTask(mode.name);
        downloadDB.close();
        //通知进度
        handler.post(new Runnable() {
            public void run() {
                DownloadCallBack callBack = getCallBack(mode);
                if (callBack != null) {
                    callBack.onResponse(mode);
                    removeTask(mode);
                }
            }
        });
    }

    //下载中
    protected synchronized void inProgress(final DownloadMode mode) {
        //存库
        DownloadDB downloadDB = new DownloadDB(LibApp.getContext());
        downloadDB.updateTask(mode);
        downloadDB.close();
        //通知进度
        handler.post(new Runnable() {
            public void run() {
                DownloadCallBack callBack = getCallBack(mode);
                if (callBack != null) {
                    callBack.inProgress(mode);
                }
            }
        });
    }
}